<?php

namespace App\Service\OpenShop\SiteLocation;

use App\Enums\BaseErrorCode;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Events\OpenShop\OpenShopProcessEvent;
use App\Events\OpenShop\SignSiteMissionEvent;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Resources\OpenShop\InvestmentPromotion\OrderDetailResource;
use App\Library\FeiShu\SendFs;
use App\Listeners\OpenShop\ProcessNoticeListener;
use App\Models\Common\ConfigModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteLocationReplayModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUploadFileResourceModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageMappingModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationCustomerAnalysisModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationProductAnalysisModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Models\Wanggui\CustomerDepartmentSiteLocationRelationModel;
use App\Models\Wanggui\CustomerDepartmentTaskModel;
use App\Remote\Rms\RmsShopRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Remote\Rms\RmsUserRoleRemote;
use App\Service\Common\SmsService;
use App\Service\OpenShop\Feishu\BaseService;
use App\Service\OpenShop\Feishu\MainProcessService;
use App\Service\OpenShop\Feishu\NoticeService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\Feishu\SiteMissionService;
use App\Service\OpenShop\Feishu\UploadFileResourceService;
use App\Service\OpenShop\FeishuMini\CustomerDepartmentService;
use App\Service\OpenShop\FeishuMini\ProgrammingService;
use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderParam;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\Rms\ShopService;
use App\Service\System\SystemNotifyService;
use App\Support\FeishuMsgSupport;
use App\Support\OrganizationManageFsRobotSendSupport;
use Carbon\Carbon;
use Exception;
use Guanguans\Notify\Factory;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Kuafu\File\FileUtil;
use Kuafu\GeneralFs\BuildFs;
use Overtrue\EasySms\Exceptions\InvalidArgumentException;
use function GuzzleHttp\Promise\all;

class SiteLocationAuditService extends BaseService
{
    private string                     $orderNo;
    private ?OpenShopSiteLocationModel $siteLocationMode;
    private int                        $rmsUserId;

    public function setOrderNo(string $orderNo): void
    {
        $this->orderNo = $orderNo;
    }

    public function setRmsUserId(int $rmsUserId): void
    {
        $this->rmsUserId = $rmsUserId;
    }

    public function setSiteLocationMode(?OpenShopSiteLocationModel $siteLocationMode): void
    {
        $this->siteLocationMode = $siteLocationMode;
    }


    /**
     * 选址审批
     * @param string $orderNo
     * @param string $content
     * @param int $status
     * @param int $rmsUserId
     * @param string $rmsUserName
     * @param int $isToStore
     * @return void
     * @throws GuzzleException
     */
    public function audit(string $orderNo, string $content, int $status, int $rmsUserId, string $rmsUserName, int $isToStore = 0): void
    {
        $this->orderNo   = $orderNo;
        $this->rmsUserId = $rmsUserId;

        // 判断审批状态
        if (!in_array($status, [OpenShopSiteLocationExamineLogModel::STATUS_OK, OpenShopSiteLocationExamineLogModel::STATUS_REFUSE])) {
            throw new ResponseHttpException(BaseErrorCode::$LOCATION_PARAM_ERR);
        }

        // 判断选址报告是否存在
        $this->siteLocationMode = OpenShopSiteLocationModel::query()
            ->whereIn('source', [
                OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                OpenShopSiteLocationModel::SOURCE_HOUSING
            ])
            ->where('orderNo', $this->orderNo)
            ->first();

        if (!$this->siteLocationMode) {
            throw new ResponseHttpException(BaseErrorCode::$ORDER_NO_ERR);
        }

        switch ($this->siteLocationMode->source) {
            case OpenShopSiteLocationModel::SOURCE_OPEN_SHOP:
                // 选址审批
                $this->handleSourceFromOpenShop($orderNo, $status, $content, $rmsUserId, $rmsUserName, $isToStore);
                break;
            case OpenShopSiteLocationModel::SOURCE_HOUSING:
                // 房源审批
                switch ($this->siteLocationMode->clueStatus) {
                    case OpenShopSiteLocationModel::CLUE_STATUS_6: // 已上架 是选址审批
                        $this->handleSourceFromOpenShop($orderNo, $status, $content, $rmsUserId, $rmsUserName, $isToStore);
                        break;
                    case OpenShopSiteLocationModel::CLUE_STATUS_3:
                    case OpenShopSiteLocationModel::CLUE_STATUS_11:
                        // 判断是否是招商经理
                        if (SiteLocationService::isSolicitBusinessManager($this->siteLocationMode->createdByUid)) {
                            $this->handleSourceFromSelfHousing($orderNo, $status, $content);
                        } else {
                            $this->handleSourceFromHousing($orderNo, $status, $content, $rmsUserId, $rmsUserName);
                        }
                        break;
                    default:
                        throw new ResponseHttpException(BaseErrorCode::$ORDER_STATUS_NOT_SUPPORT_OPERATION);
                }
                break;
        }

    }

    /**
     *
     * 房源审核
     * 审核对象：选址负责人  附加审核对象：总部负责人
     * @param string $orderNo
     * @param int $status
     * @param string $content
     * @return void
     * @throws GuzzleException
     */
    public function handleSourceFromSelfHousing(
        string $orderNo,
        int $status,
        string $content
    ) {
        $approveProcedure  = OpenShopSiteLocationExamineLogModel::APPROVE_PROCEDURE["solicitBusinessManagerApprove"];
        $siteLocationModel = OpenShopSiteLocationModel::query()
                                                      ->where('source', OpenShopSiteLocationModel::SOURCE_HOUSING)
                                                      ->where('orderNo', $orderNo)
                                                      ->first();

        $approveFunc = function () use ($approveProcedure, $siteLocationModel, $status, $content) {
            $existsApproveCount = OpenShopSiteLocationExamineLogModel::getExistsApproveCount($siteLocationModel->orderNo);
            switch ($existsApproveCount) {
                case count($approveProcedure):
                    return;
                    break;
                default:
                    $nowApproveRole         = $approveProcedure[$existsApproveCount];
                    $siteLocationUpdateData = [];
                    if ($status == OpenShopSiteLocationExamineLogModel::STATUS_OK) {
                        if ($existsApproveCount >= count($approveProcedure) - 1) {
                            //全部审批通过
                            $siteLocationUpdateData = [
                                "clueStatus"          => OpenShopSiteLocationModel::CLUE_STATUS_5,
                                "houseEvaluateStatus" => SiteLocationEnum::HOUSE_EVALUATE_STATUS_FINISH
                            ];

                            // 修改勘址任务状态
                            $statusRes = CustomerDepartmentService::updateTaskProjectPhaseBySite(OpenShopSiteLocationModel::SOURCE_HOUSING, $siteLocationModel->id, OpenShopSiteLocationModel::CLUE_STATUS_5);

                            $handlerArr = [];
                            FeishuMsgSupport::getInstance("您有一条房源审批通过！", [$siteLocationModel->createdByUid])
                                            ->setContent(
                                                ["name" => "房源所在区域", "value" => $siteLocationModel->cityArea],
                                                [
                                                    "name"  => "任务名称",
                                                    "value" => "房源审批通过"
                                                ],
                                                [
                                                    "name"  => "房源编号",
                                                    "value" => $siteLocationModel->orderNo,
                                                ],
                                                ["name" => "任务创建时间", "value" => formatDate(time())],
                                            )
                                            ->msgSend(["path" => "pages/house-source/add-source?id={$siteLocationModel->id}"]);
                        } else {
                            $nextApproveRoleIndex = $existsApproveCount + 1;
                            $handlerArr = OpenShopSiteLocationExamineLogModel::getApproveProcedureUser(
                                $approveProcedure[$nextApproveRoleIndex],
                                $siteLocationModel
                            );
                            $msgSupport           = FeishuMsgSupport::getInstance(
                                "您有一条房源待审核！",
                                $handlerArr
                            );
                            $msgSupport->setContent(
                                ["name" => "房源所在区域", "value" => $siteLocationModel->cityArea],
                                [
                                    "name"  => "任务处理角色",
                                    "value" => OpenShopSiteLocationExamineLogModel::POSITION_EXAMINE_MAPPING[$approveProcedure[$nextApproveRoleIndex]]
                                ],
                                ["name" => "任务名称", "value" => "自带址房源审核"],
                                ["name" => "任务创建时间", "value" => formatDate(time())],
                            );
                            $msgSupport->msgSend(["path" => "pages/house-source/add-source?id={$siteLocationModel->id}"]);
                            $this->siteLocationMode->update([
                                'handler' => implode(',', $handlerArr)
                            ]);
                        }
                    } else {
                        $siteLocationUpdateData = [
                            "clueStatus"          => OpenShopSiteLocationModel::CLUE_STATUS_4,
                            "houseEvaluateStatus" => SiteLocationEnum::HOUSE_EVALUATE_STATUS_WAIT
                        ];
                        $handlerArr = [$this->siteLocationMode->createdByUid];

                        FeishuMsgSupport::getInstance("您有一条房源待修改！", [$this->siteLocationMode->createdByUid])
                                        ->setContent(
                                            ["name" => "房源所在区域", "value" => $this->siteLocationMode->cityArea],
                                            [
                                                "name"  => "任务名称",
                                                "value" => "房源待修改"
                                            ],
                                            [
                                                "name"  => "任务审批角色",
                                                "value" => OpenShopSiteLocationExamineLogModel::POSITION_EXAMINE_MAPPING[$nowApproveRole]
                                            ],
                                            ["name" => "任务创建时间", "value" => formatDate(time())],
                                        )
                                        ->msgSend(["path" => "pages/house-source/add-source?id={$siteLocationModel->id}"]);
                    }

                    // 新增审批记录
                    OpenShopSiteLocationExamineLogModel::query()->insert([
                        'orderNo'      => $this->orderNo,
                        'source'       => OpenShopSiteLocationModel::SOURCE_HOUSING,
                        'position'     => $approveProcedure[$existsApproveCount],
                        'content'      => $content,
                        'status'       => $status,
                        'createdByUid' => $this->rmsUserId,
                        'updatedByUid' => $this->rmsUserId,
                        "createdAt"    => time(),
                        "updatedAt"    => time(),
                    ]);

                    if ($siteLocationUpdateData) {
                        (clone $this->siteLocationMode)->setRawAttributes(array_merge($siteLocationUpdateData, [
                            'updatedByUid' => $this->rmsUserId,
                            'handler'      => implode(',', $handlerArr),
                            'putAt'        => time(),
                            "updatedAt"    => time(),
                        ]))->save();
                    }
                    break;
            }
        };
        $approveFunc();
    }


    /**
     * 获取下一阶段审批人
     * @param $siteLocation
     * @return array|mixed
     */

    public static function getNextAuditWithHouse($siteLocation)
    {
        // 选址负责人
        $siteManagerUserIds = ConfigModel::getManager(ConfigModel::SITE_MANAGER);

        // 省总
        $provinceUserId = (new OpenShopOrganizationManageModel())->getOrganizationManageId($siteLocation->provinceCode, $siteLocation->cityCode, 1);

        $examineLogModel = OpenShopSiteLocationExamineLogModel::query()
            ->where('source', OpenShopSiteLocationModel::SOURCE_HOUSING)
            ->where('orderNo', $siteLocation->orderNo)
            ->get();

        if ($examineLogModel->count() == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_0) {
            return array_merge($siteManagerUserIds, [$provinceUserId]);
        }

        if ($examineLogModel->count() == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_1) {
            $audit = $examineLogModel->first()->createdByUid;
            if (in_array($audit, $siteManagerUserIds)) {
                return [$provinceUserId];
            } else {
                return $siteManagerUserIds;
            }
        }

//        if ($examineLogModel->count() == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_2) {
//            if ($examineLogModel->where('status', OpenShopSiteLocationExamineLogModel::STATUS_OK)->count() == 1) {
//                return ConfigModel::getManager(ConfigModel::SITE_SUPER_ADMIN);
//            }
//        }

        if ($examineLogModel->count() >= OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_2) {
             return ConfigModel::getManager(ConfigModel::SITE_SUPER_ADMIN);
        }

        return [];
    }



    /**
     * 房源审核
     * 审核对象：省总
     * @param string $orderNo
     * @param int $status
     * @param string $content
     * @param int $rmsUserId
     * @param string $rmsUserName
     * @return void
     * @throws GuzzleException
     */
    public function handleSourceFromHousing(string $orderNo, int $status, string $content, int $rmsUserId, string $rmsUserName)
    {
        // 已经审批通过了，幂等
        $audit = OpenShopSiteLocationExamineLogModel::query()
            ->where('orderNo', $orderNo)
            ->where('status', OpenShopSiteLocationExamineLogModel::STATUS_OK)
            ->count();
        if ($audit == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_1) {  //房源只审核一次
            return;
        }

        // 判断是否存在房源
        $siteLocation = OpenShopSiteLocationModel::query()
            ->where('source', OpenShopSiteLocationModel::SOURCE_HOUSING)
            ->where('orderNo', $orderNo)
            ->first();
        if ($siteLocation == null) {
            throw new ResponseHttpException(BaseErrorCode::$LOCATION_EMPTY);
        }

        // 职位是省总
        $position = OpenShopSiteLocationExamineLogModel::POSITION_PROVINCE_EXAMINE;

        if ($status == OpenShopSiteLocationExamineLogModel::STATUS_OK) {
            // 审批通过 房源上架
            $handlerArr          = [];
            $clueStatus          = OpenShopSiteLocationModel::CLUE_STATUS_5;
            $houseEvaluateStatus = SiteLocationEnum::HOUSE_EVALUATE_STATUS_FINISH;

            // 修改勘址任务状态 选址清单
            // CustomerDepartmentService::updateTaskProjectPhaseBySite(OpenShopSiteLocationModel::SOURCE_HOUSING, $siteLocation->id, OpenShopSiteLocationModel::CLUE_STATUS_5);
        } else {
            // 审批驳回 开发修改房源
            $handlerArr          = [$this->siteLocationMode->developConsultantId];
            $clueStatus          = OpenShopSiteLocationModel::CLUE_STATUS_4;
            $houseEvaluateStatus = SiteLocationEnum::HOUSE_EVALUATE_STATUS_WAIT;
        }

        $json = json_decode(sprintf(
            file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/siteNotifyToGroup.json')),
            '房源编号',
            $siteLocation->orderNo,
            $siteLocation->developConsultantName,
            SiteLocationEnum::SHOP_MODEL_TYPE_MAPPING[$siteLocation->shopModelType] ?? '-',
            SiteLocationEnum::MESSAGE_FROM_TYPE_TEXT[$siteLocation->messageFrom] ?? '-',
            $siteLocation->address,
            $siteLocation->cityArea,
            $rmsUserName,
            '省总',
            (OpenShopSiteLocationExamineLogModel::STATUS_MAPPING[$status] ?? '-'),
            Carbon::now()->format('Y-m-d H:i:s'),
            str_replace(["\n", "\r"], '\n', $content),
            BaseService::getSiteLocationAppletUrlByHouse($siteLocation->id),
            $status == OpenShopSiteLocationExamineLogModel::STATUS_OK ? 'green' : 'red',
            '【房源审核' . ($status == OpenShopSiteLocationExamineLogModel::STATUS_OK ? '同意' : '驳回') . '】 ' . $orderNo . $siteLocation->shopName . ' 房源评估审核完成，请注意'
        ), true);

        Factory::feiShu()
            ->setToken(config('feishu.robots.site_location.urlToken'))
            ->setSecret(config('feishu.robots.site_location.token'))
            ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage($json))
            ->send();

        // 新增审批记录
        OpenShopSiteLocationExamineLogModel::query()->insert([
            'orderNo'      => $this->orderNo,
            'source'       => OpenShopSiteLocationModel::SOURCE_HOUSING,
            'position'     => $position,
            'content'      => $content,
            'status'       => $status,
            'createdByUid' => $this->rmsUserId,
            'updatedByUid' => $this->rmsUserId,
            "createdAt"    => time(),
            "updatedAt"    => time(),
        ]);
        (clone $this->siteLocationMode)->setRawAttributes([
            'clueStatus'          => $clueStatus,
            'updatedByUid'        => $this->rmsUserId,
            'putAt'               => time(),
            'houseEvaluateStatus' => $houseEvaluateStatus,
            "updatedAt"           => time(),
            "handler"             => implode(',', $handlerArr),
        ])->save();

        // 审批结果同步给开发
        try {
            if ($status == OpenShopSiteLocationExamineLogModel::STATUS_OK) {
                FeishuMsgSupport::getInstance("您有一条房源审核通过！", [$this->siteLocationMode->developConsultantId])
                    ->setContent(
                        ["name" => "房源所在区域", "value" => $this->siteLocationMode->cityArea],
                        [
                            "name"  => "任务审批角色",
                            "value" => '省总',
                        ],
                        ["name" => "任务创建时间", "value" => formatDate(time())],
                    )
                    ->msgSend(["path" => "pages/house-source/add-source?id={$this->siteLocationMode->id}"]);
            } else {
                FeishuMsgSupport::getInstance("您有一条房源待修改！", [$this->siteLocationMode->developConsultantId])
                    ->setContent(
                        ["name" => "房源所在区域", "value" => $this->siteLocationMode->cityArea],
                        [
                            "name"  => "任务名称",
                            "value" => "房源待修改"
                        ],
                        [
                            "name"  => "任务审批角色",
                            "value" => '省总',
                        ],
                        ["name" => "任务创建时间", "value" => formatDate(time())],
                    )
                    ->msgSend(["path" => "pages/house-source/add-source?id={$this->siteLocationMode->id}"]);
            }
        } catch (\Exception $exception) {}

    }



    /**
     *
     * 房源审核
     * 审核对象：选址负责人  附加审核对象：总部负责人
     * @param string $orderNo
     * @param int $status
     * @param string $content
     * @param int $rmsUserId
     * @param string $rmsUserName
     * @return void
     * @throws GuzzleException
     */
    public function handleSourceFromHousingByCustomer(
        string $orderNo,
        int    $status,
        string $content,
        int    $rmsUserId,
        string $rmsUserName
    )
    {

        $siteLocation = OpenShopSiteLocationModel::query()->whereIn(
            'source',
            [
                OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                OpenShopSiteLocationModel::SOURCE_HOUSING
            ]
        )->where('orderNo', $orderNo)->first();
        if ($siteLocation == null) {
            throw new ResponseHttpException(BaseErrorCode::$LOCATION_EMPTY);
        }

        // 选址负责人
        $siteManagerUserIds = ConfigModel::getManager(ConfigModel::SITE_MANAGER);

        // 审批记录
        $examineLogModel = OpenShopSiteLocationExamineLogModel::query()
            ->where('source', OpenShopSiteLocationModel::SOURCE_HOUSING)
            ->where('orderNo', $siteLocation->orderNo)
            ->get();

        $handlerArr = [];

        if ($examineLogModel->count() == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_0) {
            // 省总
            $provinceUserId = (new OpenShopOrganizationManageModel())->getOrganizationManageId($siteLocation->provinceCode, $siteLocation->cityCode, 1);
            $position       = in_array($rmsUserId, $siteManagerUserIds) ? OpenShopSiteLocationExamineLogModel::POSITION_CHARGE_EXAMINE : OpenShopSiteLocationExamineLogModel::POSITION_PROVINCE_EXAMINE;
            $handlerArr     = in_array($rmsUserId, $siteManagerUserIds) ? [$provinceUserId] : $siteManagerUserIds;
        }

        if ($examineLogModel->count() == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_1) {
            $position   = in_array($rmsUserId, $siteManagerUserIds) ? OpenShopSiteLocationExamineLogModel::POSITION_CHARGE_EXAMINE : OpenShopSiteLocationExamineLogModel::POSITION_PROVINCE_EXAMINE;
            //$handlerArr = ConfigModel::getManager(ConfigModel::SITE_SUPER_ADMIN);

            // 调整为开发经理

        }

        if ($examineLogModel->count() >= OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_2) {
            $position = OpenShopSiteLocationExamineLogModel::POSITION_GENERAL_EXAMINE;
        }

        $delAudit = false;

        // 房源审批消息通知
        $rejectFunc = function () use ($siteLocation, $handlerArr) {
            $msgSupport = FeishuMsgSupport::getInstance(
                "您有一条房源待审核！", $handlerArr
            );

            $msgSupport->setContent(
                ["name" => "房源所在区域", "value" => $siteLocation->cityArea],
                ["name" => "任务名称", "value" => "房源审核"],
                ["name" => "任务创建时间", "value" => formatDate(time())],
            )->msgSend(["path" => "pages/house-source/add-source?id={$siteLocation->id}"]);
        };

        $clueStatus          = OpenShopSiteLocationModel::CLUE_STATUS_11;
        $houseEvaluateStatus = SiteLocationEnum::HOUSE_EVALUATE_STATUS_WAIT;
        if ($status == OpenShopSiteLocationExamineLogModel::STATUS_OK) {
            if ($examineLogModel->count() > OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_2 || $examineLogModel->where('status', OpenShopSiteLocationExamineLogModel::STATUS_OK)->count() == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_1) {
                // 审批完成
                FeishuMsgSupport::getInstance("您有一条房源审核通过！", [$this->siteLocationMode->developConsultantId])
                    ->setContent(
                        ["name" => "房源所在区域", "value" => $this->siteLocationMode->cityArea],
                        [
                            "name"  => "任务审批角色",
                            "value" => OpenShopSiteLocationExamineLogModel::POSITION_EXAMINE_MAPPING[$position] ?? '省总',
                        ],
                        ["name" => "任务创建时间", "value" => formatDate(time())],
                    )
                    ->msgSend(["path" => "pages/house-source/add-source?id={$this->siteLocationMode->id}"]);

                $handlerArr          = [];
                $clueStatus          = OpenShopSiteLocationModel::CLUE_STATUS_5;
                $houseEvaluateStatus = SiteLocationEnum::HOUSE_EVALUATE_STATUS_FINISH;

                // 修改勘址任务状态
                $statusRes = CustomerDepartmentService::updateTaskProjectPhaseBySite(OpenShopSiteLocationModel::SOURCE_HOUSING, $siteLocation->id, OpenShopSiteLocationModel::CLUE_STATUS_5);
            }

            if ($examineLogModel->count() == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_0) {
                // 给下一个审批人发消息
                $rejectFunc();
            }

            if ($examineLogModel->count() == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_1 && $examineLogModel->where('status', OpenShopSiteLocationExamineLogModel::STATUS_OK)->count() == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_0) {
                // 给开发发消息
                // 房源修改通知
                FeishuMsgSupport::getInstance("您有一条房源待修改！", [$this->siteLocationMode->developConsultantId])
                    ->setContent(
                        ["name" => "房源所在区域", "value" => $this->siteLocationMode->cityArea],
                        [
                            "name"  => "任务名称",
                            "value" => "房源待修改"
                        ],
                        [
                            "name"  => "任务审批角色",
                            "value" => OpenShopSiteLocationExamineLogModel::POSITION_EXAMINE_MAPPING[$position] ?? '省总',
                        ],
                        ["name" => "任务创建时间", "value" => formatDate(time())],
                    )
                    ->msgSend(["path" => "pages/house-source/add-source?id={$this->siteLocationMode->id}"]);
                $clueStatus = OpenShopSiteLocationModel::CLUE_STATUS_4;
            }

        } else {
            if ($examineLogModel->count() == 0) {
                // 给下一个审批人发消息
                $rejectFunc();
            }

//            if ($examineLogModel->count() == 1 && $examineLogModel->where('status', OpenShopSiteLocationExamineLogModel::STATUS_OK)->count() == 1) {
//                // 给下一个审批人发消息
//                $rejectFunc();
//            }

            // 房源修改通知
            FeishuMsgSupport::getInstance("您有一条房源待修改！", [$this->siteLocationMode->developConsultantId])
                ->setContent(
                    ["name" => "房源所在区域", "value" => $this->siteLocationMode->cityArea],
                    [
                        "name"  => "任务名称",
                        "value" => "房源待修改"
                    ],
                    [
                        "name"  => "任务审批角色",
                        "value" => OpenShopSiteLocationExamineLogModel::POSITION_EXAMINE_MAPPING[$position] ?? '省总',
                    ],
                    ["name" => "任务创建时间", "value" => formatDate(time())],
                )
                ->msgSend(["path" => "pages/house-source/add-source?id={$this->siteLocationMode->id}"]);

            if (($examineLogModel->count() == 1 && in_array($examineLogModel->where('status', OpenShopSiteLocationExamineLogModel::STATUS_OK)->count(), [OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_0, OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_1])) || $examineLogModel->count() >= 2) {
                $handlerArr = [$this->siteLocationMode->developConsultantId];
                $clueStatus = OpenShopSiteLocationModel::CLUE_STATUS_4;
                // 删除所有记录
                if ($examineLogModel->count() == 1 && $examineLogModel->where('status', OpenShopSiteLocationExamineLogModel::STATUS_OK)->count() == 0) {
                    $delAudit = true;
                }
            }
        }

        $json = json_decode(
            sprintf(
                file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/siteNotifyToGroup.json')),
                '房源编号',
                $siteLocation->orderNo,
                $siteLocation->developConsultantName,
                SiteLocationEnum::SHOP_MODEL_TYPE_MAPPING[$siteLocation->shopModelType] ?? '-',
                SiteLocationEnum::MESSAGE_FROM_TYPE_TEXT[$siteLocation->messageFrom] ?? '-',
                $siteLocation->address,
                $siteLocation->cityArea,
                $rmsUserName,
                OpenShopSiteLocationExamineLogModel::POSITION_EXAMINE_MAPPING[$position] ?? '省总',
                (OpenShopSiteLocationExamineLogModel::STATUS_MAPPING[$status] ?? '-'),
                Carbon::now()->format('Y-m-d H:i:s'),
                str_replace(["\n", "\r"], '\n', $content),
                BaseService::getSiteLocationAppletUrlByHouse($siteLocation->id),
                $status == OpenShopSiteLocationExamineLogModel::STATUS_OK ? 'green' : 'red',
                '【房源审核' . ($status == OpenShopSiteLocationExamineLogModel::STATUS_OK ? '同意' : '驳回') . '】 ' . $orderNo . $siteLocation->shopName . ' 房源评估审核完成，请注意'
            ), true
        );

        Factory::feiShu()
            ->setToken(config('feishu.robots.site_location.urlToken'))
            ->setSecret(config('feishu.robots.site_location.token'))
            ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage($json))
            ->send();

        // 新增审批记录
        OpenShopSiteLocationExamineLogModel::query()->insert([
            'orderNo'      => $this->orderNo,
            'source'       => OpenShopSiteLocationModel::SOURCE_HOUSING,
            'position'     => $position,
            'content'      => $content,
            'status'       => $status,
            'createdByUid' => $this->rmsUserId,
            'updatedByUid' => $this->rmsUserId,
            "createdAt"    => time(),
            "updatedAt"    => time(),
        ]);

        // 删除所有审批
        if ($delAudit) {
            OpenShopSiteLocationExamineLogModel::query()
                ->where('orderNo', $siteLocation->orderNo)
                ->get()
                ->each(function (OpenShopSiteLocationExamineLogModel $examineLogModel) {
                    $examineLogModel->isDeleted = 1;
                    $examineLogModel->save();
                });
        }

        (clone $this->siteLocationMode)->setRawAttributes([
            'clueStatus'          => $clueStatus,
            'updatedByUid'        => $this->rmsUserId,
            'putAt'               => time(),
            'houseEvaluateStatus' => $houseEvaluateStatus,
            "updatedAt"           => time(),
            "handler"             => implode(',', $handlerArr),
        ])->save();
    }


    /**
     * 选址审批
     * @param string $orderNo
     * @param int $status
     * @param string $content
     * @param int $rmsUserId
     * @param string $rmsUserName
     * @param int $isToStore
     * @throws GuzzleException|InvalidArgumentException
     */
    public function handleSourceFromOpenShop(string $orderNo, int $status, string $content, int $rmsUserId, string $rmsUserName, int $isToStore = 0)
    {
        // 已经审批通过了，幂等
        $siteLocationExamineLogModel = OpenShopSiteLocationExamineLogModel::query()
            ->withoutGlobalScope('isDel')
            ->where("type", OpenShopSiteLocationExamineLogModel::TYPE_DEFAULT)
            ->where("source", OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)
            ->where('orderNo', $orderNo);

        // 获得审批职位信息
        $auditPosition = $siteLocationExamineLogModel
            ->where('status', OpenShopSiteLocationExamineLogModel::STATUS_OK)
            ->where('isDeleted', 0)
            ->pluck('createdByUid', 'position')
            ->toArray();

        // 判断是否存在数据调整
        $isDataAlignment = false;
        $siteLocationExamineLogModel->get()
            ->each(function (OpenShopSiteLocationExamineLogModel $examineLogModel) use (&$isDataAlignment) {
                if (false !== strpos($examineLogModel->content, '【仅数据调整】')) {
                    $isDataAlignment = true;
                } elseif (false !== strpos($examineLogModel->content, '【重新选址】')) {
                    $isDataAlignment = false;
                }
            });

        // 选址报告已审批通过数量
        $statusOkCount = $siteLocationExamineLogModel
            ->where('status', OpenShopSiteLocationExamineLogModel::STATUS_OK)
            ->where('isDeleted', 0)
            ->count();

        if ($statusOkCount == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_5) {
            return;
        }

        // 获得选址信息
        $siteLocation = OpenShopSiteLocationModel::query()
            ->with(['signOrderRel', "openShopMainProcessRel"])
            ->whereIn('source', [
                OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                OpenShopSiteLocationModel::SOURCE_HOUSING
            ])
            ->where('orderNo', $orderNo)
            ->first();
        if (null === $siteLocation) {
            return;
        }

        // 获取省区处理人
        $provinceInfoBy = OrganizationManageService::getProvinceInfoByProvinceCode($siteLocation->provinceCode, $siteLocation->cityCode, 1);
        //核查专员
        $verifyPersonnel = ConfigModel::getManager(ConfigModel::VERIFY_PERSONNEL);
        //总部负责人
        $superAdmin = ConfigModel::getManager(ConfigModel::SITE_SUPER_ADMIN);
        //选址负责人
        $siteManage = ConfigModel::getManager(ConfigModel::SITE_MANAGER);
        // 战区负责人
        $warZoneManage = OpenShopRegionManageModel::getWarZoneInfoByProvinceCode($siteLocation->provinceCode)['userId'] ?? 0;

        //复盘幂等
        $replayCount = OpenShopSiteLocationReplayModel::query()
            ->where('createdByUid', $rmsUserId)
            ->where('orderNo', $this->orderNo)
            ->count();

        if (!$replayCount) {
            //添加复盘
            OpenShopSiteLocationReplayModel::query()->create([
                'content'      => '',
                'orderNo'      => $this->orderNo,
                'createdByUid' => $rmsUserId,
                'updatedByUid' => $rmsUserId,
            ]);
        }

        // 是否事先通知筹备
        $priorNotice = false;

        $positionText = '';
        $approveText  = '';
        switch ($statusOkCount) {
            case OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_0:
            case OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_1:
            case OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_2:
            case OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_3:
                if ($statusOkCount == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_3) {
                    $positionText = '核实专员';
                    $approveText  = '核实';
                    $position     = OpenShopSiteLocationExamineLogModel::POSITION_VERIFY_PERSONNEL;
                } elseif ($statusOkCount == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_2) {
                    $positionText = '选址负责人';
                    $position     = OpenShopSiteLocationExamineLogModel::POSITION_CHARGE_EXAMINE;
                    $approveText  = '审批';
                } else {
                    // 获得已经审批的职位
                    if (in_array(OpenShopSiteLocationExamineLogModel::POSITION_WAR_ZONE_MANAGER, array_keys($auditPosition))) {
                        $position     = OpenShopSiteLocationExamineLogModel::POSITION_PROVINCE_EXAMINE;
                        $positionText = '省总';
                        if (isset($provinceInfoBy['type']) && $provinceInfoBy['type'] == OpenShopOrganizationManageUserModel::TYPE_DEVELOP_CITY_MANAGER) {
                            $positionText = '开发城市经理';
                        }
                    } else {
                        // 判断当前用户是否是省总
                        if ($provinceInfoBy['operationUid'] == $rmsUserId) {
                            $position     = OpenShopSiteLocationExamineLogModel::POSITION_PROVINCE_EXAMINE;
                            $positionText = '省总';
                            if (isset($provinceInfoBy['type']) && $provinceInfoBy['type'] == OpenShopOrganizationManageUserModel::TYPE_DEVELOP_CITY_MANAGER) {
                                $positionText = '开发城市经理';
                            }
                        } else {
                            $positionText = '战区负责人';
                            $position     = OpenShopSiteLocationExamineLogModel::POSITION_WAR_ZONE_MANAGER;
                        }
                    }
                    $approveText = '审批';
                }

                // 添加审批记录
                (new OpenShopSiteLocationExamineLogModel([
                    'orderNo'      => $this->orderNo,
                    'content'      => $content,
                    'isToStore'    => $isToStore,
                    'position'     => $position,
                    'status'       => $status,
                    'createdByUid' => $this->rmsUserId,
                    'updatedByUid' => $this->rmsUserId,
                ]))->addData();

                // 执行下一步操作
                if ($status == OpenShopSiteLocationExamineLogModel::STATUS_OK) {    //审批通过
                    if ($statusOkCount == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_3) {
                        //状态变为待审核
                        $this->auditStatusPending(OpenShopSiteLocationModel::SITE_STATUS_11, $superAdmin);
                        try {
                            //推送飞书消息 选址负责人和省总以及核查专员审批完成 给总部负责人推送消息
                            $noticeServer = new NoticeService($this->orderNo, $rmsUserId);
                            $noticeServer->setPushUserInfos($superAdmin);
                            $noticeServer->setMissionContent('选址表单待审核');
                            $noticeServer->siteLocationAuditJob('审核');
                        } catch (\Exception $exception) {}
                    }
                    if ($statusOkCount == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_2) {
                        $this->setHandler($verifyPersonnel);
                        // 给核实人员推送消息
                        $noticeServer = new NoticeService($this->orderNo, $rmsUserId);
                        $noticeServer->setPushUserInfos($verifyPersonnel);
                        $noticeServer->setMissionContent('选址信息核实');
                        $noticeServer->siteLocationAuditJob('核实');
                    }
                    if ($statusOkCount == OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_1) {
                        // 省总和战区负责人已经审批通过 提前通知筹备
                        $priorNotice = true;

                        // 设置选址负责人
                        $this->setHandler($siteManage);

                        // 通知选址负责人
                        try {
                            $noticeServer = new NoticeService($this->orderNo, $rmsUserId);
                            $noticeServer->setPushUserInfos($siteManage);
                            $noticeServer->setMissionContent('选址表单待审批');
                            $noticeServer->siteLocationAuditJob('审批');
                        } catch (\Exception $exception) {}
                    }
                    if ($statusOkCount == 0) {
                        $handler = explode(',', $this->siteLocationMode->handler);
                        // 处理省总和战区总是同一个人
                        if (count($handler) == 1) {
                            // 添加审批记录
                            OpenShopSiteLocationExamineLogModel::query()
                                ->insert([
                                    'orderNo'      => $this->orderNo,
                                    'content'      => '【系统自动通过】之前已通过该审批，无需重复审批',
                                    'isToStore'    => $isToStore,
                                    'position'     => OpenShopSiteLocationExamineLogModel::POSITION_WAR_ZONE_MANAGER,
                                    'status'       => $status,
                                    'createdByUid' => $warZoneManage,
                                    'updatedByUid' => $warZoneManage,
                                    'createdAt'    => time(),
                                    'updatedAt'    => time(),
                                ]);

                            // 设置选址负责人
                            $this->setHandler($siteManage);

                            // 通知选址负责人
                            try {
                                $noticeServer = new NoticeService($this->orderNo, $rmsUserId);
                                $noticeServer->setPushUserInfos($siteManage);
                                $noticeServer->setMissionContent('选址表单待审批');
                                $noticeServer->siteLocationAuditJob('审批');
                            } catch (\Exception $exception) {}

                            // 通知筹备
                            $priorNotice = true;
                        } else {
                            if ($position == OpenShopSiteLocationExamineLogModel::POSITION_WAR_ZONE_MANAGER) {
                                $this->setHandler([$provinceInfoBy['operationUid']]);
                            } else {
                                $this->setHandler([$warZoneManage]);
                            }
                        }
                    }
                } else {  //审批拒绝
                    //状态变为已驳回
                    $this->auditRefuse();
                    try {
                        // 发送飞书推送
                        $noticeServer = new NoticeService($this->orderNo, $rmsUserId);
                        $noticeServer->setPushUserInfos([$this->siteLocationMode->developConsultantId]);
                        $noticeServer->setMissionContent('选址表单待修改');
                        $noticeServer->siteLocationAuditJobWithResponsible($content);
                    } catch (\Exception $exception) {}
                }
                break;
            case OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_4:
                $positionText = '总部负责人';
                $approveText  = '审核';
                //新增审批记录
                (new OpenShopSiteLocationExamineLogModel([
                    'orderNo'      => $this->orderNo,
                    'content'      => $content,
                    'position'     => OpenShopSiteLocationExamineLogModel::POSITION_GENERAL_EXAMINE,  // 总部负责人
                    'isToStore'    => $isToStore,
                    'status'       => $status,
                    'createdByUid' => $this->rmsUserId,
                    'updatedByUid' => $this->rmsUserId,
                ]))->addData();

                if ($status == OpenShopSiteLocationExamineLogModel::STATUS_OK) {  // 审批通过

                    //同步open_shop_location
                    $this->auditOk($isDataAlignment ? OpenShopSiteLocationModel::SITE_STATUS_21 : OpenShopSiteLocationModel::SITE_STATUS_20);
                    $this->auditOkEvent();
                    $this->setHandler([]);

                    // 仅数据调整 - 更新选址信息
                    if ($isDataAlignment) {
                        OpenShopAddressModel::autoAdd($orderNo);
                    }

                    $mainProcess = OpenShopMainProcessModel::query()->where('orderNo', $orderNo)->first();
                    $signOrder   = OpenShopSignOrderModel::query()->where('orderNo', $orderNo)->first();

                    // 发送通知
                    $notify = SystemNotifyService::save(
                        false,
                        '开店进度提示',
                        SystemNotifyCenterModel::NOTIFY_TYPE_4,
                        SystemNotifyCenterModel::NOTIFY_TARGET_1,
                        '',
                        '您的选址报告已经通过啦！快来确认！',
                        'kuafoodmerchantapp://openSchedule',
                        SystemNotifyCenterModel::METHOD_TYPE_AUTOMATIC,
                        "您的选址报告已经通过啦！快来确认！",
                        '',
                        SystemNotifyCenterModel::IS_POPUP_ON,
                        1,
                        $mainProcess->shopId,
                    );
                    SystemNotifyService::recordLog($notify, '创建消息');
                    SystemNotifyService::preSend($notify->id, [$signOrder->merchantUserId]);

                    //更新线索状态  变为已成交
                    OpenShopSiteLocationModel::query()
                        ->where('orderNo', $orderNo)
                        ->whereIn('source', [
                            OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                            OpenShopSiteLocationModel::SOURCE_HOUSING
                        ])
                        ->update([
                            'clueStatus' => OpenShopSiteLocationModel::CLUE_STATUS_6,
                            'updatedAt'  => time(),
                        ]);

                    try {
                        //推送飞书消息
                        $noticeServer = new NoticeService($this->orderNo, $rmsUserId);
                        $noticeServer->setPushUserInfos(ProcessNoticeListener::historyUidsByOrderNo($this->orderNo));
                        $noticeServer->siteLocationAuditHistoryByCharge(); // 推送
                    } catch (\Exception $exception) {}

                    //选址报告审批通过 同步更新rms门店信息
                    RmsShopRemote::synchronizeShopInfo(
                        $siteLocation->openShopMainProcessRel->shopId,
                        $siteLocation->address,
                        $siteLocation->cityArea,
                        (string)$siteLocation->provinceCode,
                        (string)$siteLocation->cityCode,
                        (string)$siteLocation->areaCode,
                        (string)$siteLocation->longitude,
                        (string)$siteLocation->latitude,
                    );

                    $smsMsgSend = function () use ($rmsUserId, $orderNo) {
                        $signOrderModel = OpenShopSignOrderModel::query()
                            ->where("orderNo", $orderNo)
                            ->first();
                        //发送阿里云短信
                        (new SmsService())->aliyunSend(
                            $signOrderModel->baseInfoRel->mobile,
                            config('sms.template.siteLocationApprovalPass'),
                            ["shopCode" => $signOrderModel->getAttribute("shopCode")],
                        );
                    };
                    //短信通知
                    $smsMsgSend();

                    try {
                        FeishuMsgSupport::getInstance('有新的选址表单已提交，请及时沟通', array_merge([$provinceInfoBy['operationUid']], $siteManage))
                            ->setContent(
                                ["name" => "选址所在区域", "value" => $siteLocation->cityArea],
                                ["name" => "任务处理角色", "value" => "总部负责人"],
                                ["name" => "任务名称", "value" => "选址表单完成审批"],
                                ["name" => '审核时间', "value" => formatDate(time())],
                                [
                                    "name"  => '审核结果',
                                    "value" => (OpenShopSiteLocationExamineLogModel::STATUS_MAPPING[$status] ?? '-')
                                ],
                                ["name" => '审核详情', "value" => $content],
                            )
                            ->msgSend(["path" => "pages/site-info/index?orderNo={$siteLocation->orderNo}"]);
                    } catch (\Exception $exception) {}
                } else {
                    //状态变为已驳回
                    $this->auditRefuse();

                    // 发送飞书推送
                    $noticeServer = new NoticeService($this->orderNo, $rmsUserId);
                    $noticeServer->setPushUserInfos([$this->siteLocationMode->developConsultantId]);
                    $noticeServer->setMissionContent('选址表单待修改');
                    try {
                        $noticeServer->siteLocationAuditJobWithResponsible($content);
                        FeishuMsgSupport::getInstance('有新的选址报告审核完成，请查看', array_merge([$provinceInfoBy['operationUid']], $siteManage))
                            ->setContent(
                                ["name" => "选址所在区域", "value" => $siteLocation->cityArea],
                                ["name" => "门店编号", "value" => (int)optional($siteLocation->signOrderRel)->shopCode],
                                ["name" => "任务处理角色", "value" => "总部负责人"],
                                ["name" => "任务名称", "value" => "选址表单完成审批"],
                                ["name" => '审核时间', "value" => formatDate(time())],
                                [
                                    "name"  => '审核结果',
                                    "value" => (OpenShopSiteLocationExamineLogModel::STATUS_MAPPING[$status] ?? '-')
                                ],
                                ["name" => '审核详情', "value" => $content],
                            )
                            ->msgSend(["path" => "pages/site-info/index?orderNo={$siteLocation->orderNo}"]);
                    } catch (\Exception $exception) {}
                }
                break;
            default:
        }

        //获得跳转的curl
        $json = json_decode(sprintf(
            file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/siteNotifyToGroup.json')),
            '门店编号',
            (int)optional($siteLocation->signOrderRel)->shopCode,
            $siteLocation->developConsultantName,
            SiteLocationEnum::SHOP_MODEL_TYPE_MAPPING[$siteLocation->shopModelType] ?? '-',
            SiteLocationEnum::MESSAGE_FROM_TYPE_TEXT[$siteLocation->messageFrom] ?? '-',
            $siteLocation->address,
            $siteLocation->cityArea,
            $rmsUserName,
            $positionText,
            (OpenShopSiteLocationExamineLogModel::STATUS_MAPPING[$status] ?? '-'),
            Carbon::now()->format('Y-m-d H:i:s'),
            str_replace(["\n", "\r"], '\n', $content),
            BaseService::getSiteLocationAppletUrl(0, $orderNo),
            $status == OpenShopSiteLocationExamineLogModel::STATUS_OK ? 'green' : 'red',
            '【选址' . $approveText . ($status == OpenShopSiteLocationExamineLogModel::STATUS_OK ? '同意' : '驳回') . '】' . (int)optional($siteLocation->signOrderRel)->shopCode . $siteLocation->shopName . ' 有新的选址评估' . $approveText . '完成，请注意'
        ), true);

        Factory::feiShu()
               ->setToken(config('feishu.robots.site_location.urlToken'))
               ->setSecret(config('feishu.robots.site_location.token'))
               ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage($json))
               ->send();

        // 提前通知筹备
        if ($priorNotice && 'prod' == config('app.env')) {
            BuildFs::newRobot(0, BuildFs::MSG_TYPE_CARD)
                ->setRobotConfig('https://open.feishu.cn/open-apis/bot/v2/hook/a3458162-b7db-4f6b-9f36-98978d2c33e9', 'LsmVFx0rk52tC0uQzW7Hke')
                ->setCardContent($json)
                ->send();
        }
    }

    private function auditOk($siteStatus = OpenShopSiteLocationModel::SITE_STATUS_20)
    {
        // 审批日志
        //        $examine = OpenShopSiteLocationExamineLogModel::query()
        //                                                      ->where("source", OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)
        //                                                      ->where('orderNo', $this->orderNo)
        //                                                      ->where('position', OpenShopSiteLocationExamineLogModel::POSITION_CHARGE_EXAMINE)
        //                                                      ->where('status', OpenShopSiteLocationExamineLogModel::STATUS_OK)
        //                                                      ->count();
        //        if ($examine) {
        //            throw new ResponseHttpException(BaseErrorCode::$SITE_LOCATION_HAS_AUDIT);
        //        }

        // 开店流程中的选址信息
        $location = OpenShopLocationModel::query()->where('orderNo', $this->orderNo)->first();
        if (!$location) {
            throw new ResponseHttpException(BaseErrorCode::$LOCATION_EMPTY);
        }

        if ($location->status == MainProcessEnum::SHOP_LOCATION_CONFIRM) {
            throw new ResponseHttpException(BaseErrorCode::$LOCATION_HAS_CONFIRM);
        }

        $location->update([
            //                'mainProcessId'          => $mainProcessId,
            //                'orderNo'                => $orderNo,
            //                'assignTime'             => '',
            'investmentManagerId'   => $this->siteLocationMode->developConsultantId,
            'investmentManagerName' => $this->siteLocationMode->developConsultantName,
            'step'                  => MainProcessEnum::SHOP_LOCATION_FORM_SUBMIT,
            //            'shopLocationReportUrl'  => '', // 选址报告
            //            'shopLocationReportLink' => '', // 伙伴云选址报告链接
            'submitReportTime'      => $this->siteLocationMode->createdAt->timestamp,
            'confirmStatus'         => OpenShopLocationModel::CONFIRM_STATUS_OFF,
            'confirmTime'           => 0,
            'shopAddressPrefix'     => $this->siteLocationMode->cityArea,
            'provinceCode'          => $this->siteLocationMode->provinceCode,
            'cityCode'              => $this->siteLocationMode->cityCode,
            'districtCode'          => $this->siteLocationMode->areaCode,
            'shopDetailAddress'     => $this->siteLocationMode->address,
            'rentPer'               => $this->siteLocationMode->remind,
            'monthlyRent'           => SiteLocationConvert::monthlyRent($this->siteLocationMode->rentType),
            'shopRent'              => (int)($this->siteLocationMode->fixedRent / 12),
            'shopArea'              => $this->siteLocationMode->area,
            'shopType'              => SiteLocationConvert::shopType($this->siteLocationMode->siteType),
            //            'averageDailyBreak'      => 0, // 日均保本点
            //            'averageDaily'           => 0', // 日均收益
            'isLocationSelf'        => SiteLocationConvert::isLocationSelf($this->siteLocationMode->messageFrom),
            // 是否自带选址
            'payMonth'              => SiteLocationEnum::RENT_PAYMENT_MONTH[$this->siteLocationMode->rentPaymentCycle] ?? 0,
            // 支付月数
            'depositMonth'          => 0,
            // 押金月数
            'locationType'          => OpenShopLocationModel::LOCATION_TYPE_0,
            // 0未选择 1现场评估 2远程评估
            'shopScopeProducts'     => SiteLocationConvert::shopScopeProducts($this->siteLocationMode->restrictedSales),
            // 产品限制销售范围
            'electricQuantity'      => $this->siteLocationMode->electricityConsumption,
            'isAddElectricNum'      => $this->siteLocationMode->isCapacityIncrease,
            'smokeNumber'           => $this->siteLocationMode->exhaustAirVolume,
            'isReformSmoke'         => $this->siteLocationMode->isExhaustReconstruction,
            'upperWaterDiameter'    => $this->siteLocationMode->upperWaterDiameter,
            'lowerWaterDiameter'    => $this->siteLocationMode->lowerWaterDiameter,
            'isReformWater'         => $this->siteLocationMode->isReformWater,
            'cashType'              => SiteLocationConvert::cashType($this->siteLocationMode->caseRegisterType),
            'openTime'              => $this->siteLocationMode->openTime,
            'updatedByUid'          => $this->rmsUserId,
            'deposit'               => $this->siteLocationMode->deposit,
        ]);

        // 状态调整为已通过
        $this->siteLocationMode->setStatusOk($this->rmsUserId, $siteStatus);
    }

    private function auditRefuse()
    {
        // 状态调整为已驳回
        $this->siteLocationMode->setStatusFail($this->rmsUserId);
    }

    private function auditStatusPending($status, $superAdmin)
    {
        // 状态调整为省总已审批  待选址负责人审批
        $this->siteLocationMode->setStatusPending($this->rmsUserId, $status, $superAdmin);
    }

    private function setHandler($userIds)
    {
        // 状态调整为省总已审批  待选址负责人审批
        $this->siteLocationMode->setHandler($userIds);
    }

    private function auditOkEvent()
    {
        $shopName      = '';
        $mainProcessId = (int)OpenShopMainProcessModel::query()->where('orderNo', $this->orderNo)->value('id');

        // 更新门店名称
        //        ShopService::updateShopName($this->orderNo, $shopName);

        //        $missionId = SiteMissionService::genMission($this->orderNo, MissionTemplateEnum::STEP_STATUS_4);
        //        OpenShopSiteMissionModel::query()->where('id', $missionId)->update(['status' => SiteMissionEnum::STATUS_2]);

        event(
            new SignSiteMissionEvent(
                $this->orderNo, MissionTemplateEnum::STEP_STATUS_4,
                $this->siteLocationMode->developConsultantId
            )
        );
        event(
            new OpenShopProcessEvent(
                $this->siteLocationMode->developConsultantId, $mainProcessId,
                MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION,
                MainProcessEnum::SHOP_LOCATION_FORM_SUBMIT
            )
        );
    }
}

class SiteLocationConvert
{
    public static function cashType(int $caseRegisterType)
    {
        return [
                SiteLocationEnum::CASE_REGISTER_TYPE_1 => OpenShopLocationModel::CASH_TYPE_2,
                SiteLocationEnum::CASE_REGISTER_TYPE_2 => OpenShopLocationModel::CASH_TYPE_1,
                SiteLocationEnum::CASE_REGISTER_TYPE_3 => OpenShopLocationModel::CASH_TYPE_3,
//                SiteLocationEnum::CASE_REGISTER_TYPE_4 => OpenShopLocationModel::CASH_TYPE_4,
            ][$caseRegisterType] ?? OpenShopLocationModel::CASH_TYPE_2;
    }

    public static function shopType(int $siteType)
    {
        switch ($siteType) {
            case SiteLocationEnum::SITE_TYPE_18:
            case SiteLocationEnum::SITE_TYPE_1:
            case SiteLocationEnum::SITE_TYPE_2:
            case SiteLocationEnum::SITE_TYPE_3:
            case SiteLocationEnum::SITE_TYPE_4:
                return '商场店';
            case SiteLocationEnum::SITE_TYPE_5:
            case SiteLocationEnum::SITE_TYPE_6:
            case SiteLocationEnum::SITE_TYPE_7:
            case SiteLocationEnum::SITE_TYPE_8:
                return '街边店';
            case 0:
                return '-';
            default:
                return '特殊店';
        }
    }

    public static function shopScopeProducts(string $restrictedSales): string
    {
        $res = '';
        $arr = explode(',', $restrictedSales);
        foreach ($arr as $v) {
            $res .= SiteLocationEnum::RESTRICTED_SALES_TEXT[$v] ?? '';
            $res .= ',';
        }

        return rtrim($res, ',');
    }

    public static function isLocationSelf(int $messageFrom): int
    {
        if ($messageFrom == SiteLocationEnum::MESSAGE_FROM_TYPE_1) {
            return OpenShopLocationModel::IS_SELF_LOCATION_1;
        }

        return OpenShopLocationModel::IS_SELF_LOCATION_0;
    }

    public static function monthlyRent(int $rentType)
    {
        return [
                SiteLocationEnum::RENT_TYPE_1 => OpenShopLocationModel::MONTH_RENT_0,
                SiteLocationEnum::RENT_TYPE_2 => OpenShopLocationModel::MONTH_RENT_1,
                SiteLocationEnum::RENT_TYPE_3 => OpenShopLocationModel::MONTH_RENT_2,
                SiteLocationEnum::RENT_TYPE_4 => OpenShopLocationModel::MONTH_RENT_3,
            ][$rentType] ?? 0;
    }
}
